package com.rfid.a252robot.widget;

import android.content.Context;
import android.text.method.KeyListener;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;

import java.util.ArrayList;
import java.util.List;

public class KeyParentLayout extends TableLayout implements View.OnClickListener {

    List<Button> mButtons = new ArrayList<>();
    KeyListener mKeyListener;

    public KeyParentLayout(Context context) {
        super(context);
    }

    public KeyParentLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mButtons.clear();
        int count = getChildCount();
        for (int i=0;i<count;i++) {
            View v = getChildAt(i);
            System.out.println(v);
            if (v instanceof TableRow) {
                int c = ((TableRow) v).getChildCount();
                for (int j=0;j<c;j++) {
                    View b = ((TableRow) v).getChildAt(j);
                    System.out.println(b.getClass().getName());
                    if (b instanceof Button) {
                        mButtons.add((Button) b);
                        b.setOnClickListener(this);
                    }
                }
            }
        }
        System.out.println("mButtons size = " + mButtons.size());
    }

    @Override
    public void onClick(View v) {
        System.out.println("onClick");
        if (mKeyListener != null) {
            if (v instanceof Button) {
                String text = ((Button) v).getText().toString();
                if ("←".equals(text)) {
                    mKeyListener.onDelete();
                } else if ("*".equals(text)) {
                } else {
                    mKeyListener.onKey(text);
                }
            }
        }
    }

    public void setKeyListener(KeyListener listener) {
        mKeyListener = listener;
    }

    public interface KeyListener {

        public void onKey(String key);

        public void onDelete();
    }
}
